﻿using System;
using System.IO;
using Elight.Entity.GlobalData;
using Elight.Logic.Base;
using Elight.Utility.Core;
using Elight.Utility.Extension;
using Elight.Utility.Logs;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Elight.WebUI
{
    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                ServerConfigs config = File.ReadAllText(MyEnvironment.RootPath("Configs/config.json")).ToObject<ServerConfigs>();
                GlobalValue.Config = config;
                string message = "";
                bool flag = BaseLogic.InitDB(config.DbType, config.DbHost, config.DbName, config.DbUserName, config.DbPassword, ref message, config.Debug);
                if (!flag)
                {
                    Console.Write(message);
                    return;
                }
                LogHelper.Init(MyEnvironment.RootPath("Configs/log4net.config"));
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            if (GlobalValue.Config.IISDeploy)
            {
                return Host.CreateDefaultBuilder(args)
                     .ConfigureWebHostDefaults(webBuilder =>
                     {
                         webBuilder.UseContentRoot(MyEnvironment.RootPath(""));
                         webBuilder.UseWebRoot(MyEnvironment.RootPath("wwwroot"));
                         webBuilder.UseStartup<Startup>();
                     });
            }
            else
            {
                return Host.CreateDefaultBuilder(args)
                         .ConfigureLogging(logging =>
                         {
                             logging.ClearProviders();
                             if (GlobalValue.Config.Debug)
                                 logging.AddConsole();
                         })
                         .ConfigureWebHostDefaults(webBuilder =>
                         {
                             webBuilder.UseUrls($"http://*:{GlobalValue.Config.HttpPort}");
                             webBuilder.UseContentRoot(MyEnvironment.RootPath(""));
                             webBuilder.UseWebRoot(MyEnvironment.RootPath("wwwroot"));
                             webBuilder.UseKestrel(options =>
                             {
                                 options.Limits.MaxRequestBodySize = null;
                             });
                             webBuilder.UseStartup<Startup>();
                         });
            }
        }
    }
}
